var activity_id="";
var chk_value_str = "";//用于保存已选择的商品，
var chk_value_str_del = "";//用于保存已删除的商品id
$(function () {
	
	var re = /^[0-9]+.?[0-9]*$/;   //判断字符串是否为数字
	
	//是否自动抽奖
	$("[name='isAutoDraw']").click(function(){
		if($(this).val() == 1){//自动抽奖，隐藏"抽奖背景图"、"中奖背景图"操作
			$("#get_div").hide();
			//$("#win_div").hide();
		}else{
			$("#get_div").show();
			//$("#win_div").show();
		}
	});
	
	//选择商品modal，操作checkbox
	//全选
	$("#selectAll").click(function() {
		$("input[name='product']").prop("checked", $(this).is(':checked'));
	}); 
	//当列表中所有复选框选中，全选按钮选中，否则不选中
	$("input[name='product']").change(function(){
		$("#selectAll").prop("checked",!($("input[name='product']").length - $("input[name='product']:checked").length));
	});
	
	
	$('#activity_start_new').daterangepicker({
		"singleDatePicker": true,
		"timePicker": true,
		"timePicker24Hour": true,
		"timePickerSeconds": true,
		"parentEl": "200",
		
		locale: {
		  format:'YYYY-MM-DD HH:mm:ss',
	      applyLabel: '确认',
	      cancelLabel: '取消',
	      weekLabel: 'W',
	      customRangeLabel: 'Custom Range',
	      daysOfWeek:["日","一","二","三","四","五","六"],
	      monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
		}
	}, function(start, end, label) {
		$('#activity_start_new').val(start.format('YYYY-MM-DD HH:mm:ss'));
 		
	});
	
	$('#activity_end_new').daterangepicker({
		"singleDatePicker": true,
		"timePicker": true,
		"timePicker24Hour": true,
		"timePickerSeconds": true,
		"parentEl": "200",
		locale: {
		  format:'YYYY-MM-DD HH:mm:ss',
	      applyLabel: '确认',
	      cancelLabel: '取消',
	      weekLabel: 'W',
	      customRangeLabel: 'Custom Range',
	      daysOfWeek:["日","一","二","三","四","五","六"],
	      monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
		}
	}, function(start, end, label) {
		$('#activity_end_new').val(start.format('YYYY-MM-DD HH:mm:ss'));
	});
	
	//取消活动
	$("[name='btn_cancel_new_activity']").click(function(){
		window.location.href="/activity";
	});
    //保存创建的活动
    $("[name='btn_save_new_activity']").click(function () {
        var form = window.form_new_activity;
        var name = form.name.value;//活动名称
        if(!name){
        	bootbox.balert("活动名称必须填写!");
        	return;
        }
        
        var selectedProducts = chk_value_str;
        var num = $("[id^=regionDiv]").length;
        var str="";
        var str1 ="";
        var str2 = "";
        var str_="",str3="",str4="";        
        var selectRgn="";//保存选择的区域id
        for(var i = 0; i < num; i++){
        	if(i==0){
        		
        			str = $("[id^=regionDiv]").find("select:eq(0) option:selected").val();
            		str1 = $("[id^=regionDiv]").find("select:eq(1) option:selected").val();
            		str2 = $("[id^=regionDiv]").find("select:eq(2) option:selected").val();
            		if(str!=""){
            		if(str2 != "" && typeof(str2) != 'undefined'){
            			if(selectRgn.indexOf(str2)<0){
            				selectRgn += str2+",";
            			}
            			
            		}else{
            			if(str1 != "" && typeof(str1) != 'undefined'){
            				if(selectRgn.indexOf(str1)<0){
            					selectRgn += str1+",";
            				}
            				
            			}else{
            				if(str != "" && typeof(str) != 'undefined'){
	            				if(selectRgn.indexOf(str)<0){
	            					selectRgn += str+",";
	            				}
            				}
            			}
            		}
        		}
        		
        	}else{
        		
        			str_ = $("[name='regionDiv"+i+"']").find("select:eq(0) option:selected").val();
            		str3 = $("[name='regionDiv"+i+"']").find("select:eq(1) option:selected").val();
            		str4 = $("[name='regionDiv"+i+"']").find("select:eq(2) option:selected").val();
            		if(str_ !=""){
            		if(str4 != "" && typeof(str4) != 'undefined'){
            			if(selectRgn.indexOf(str4)<0){
            				selectRgn += str4+",";
            			}
            			
            		}else{
            			if(str3 != "" && typeof(str3) != 'undefined'){
            				if(selectRgn.indexOf(str3)<0){
            					selectRgn += str3+",";
            				}
            				
            			}else{
            				if(str_ != "" && typeof(str_) != 'undefined'){
            					if(selectRgn.indexOf(str_)<0){//判断不能有重复区域
            						selectRgn += str_+",";
            					}
            					
            				}
            			}
            		}
        		}
        		
        	}
        	
        }
        if(selectRgn==""){
        	bootbox.balert("请选择活动区域!");
            return false;
        }
        
        var actTimeStart = $('#activity_start_new').val();
        var actTimeEnd =  $('#activity_end_new').val();
        if(actTimeStart=="" || actTimeEnd==""){
        	
            	bootbox.balert("请选择活动时间!");
                return false;
             
        }
        
        //渠道
        var chk_channel = "";
        var flag = true;
        
        $('input[name="channel"]:checked').each(function(){
        	
        	if($(this).val() == "自定义"){
        		if($("#channel_custom").val() == null || $("#channel_custom").val()==""){
        			bootbox.balert("渠道为自定义，必须填写自定义说明!");
                    flag = false;
        		}
        		chk_channel += $("#channel_custom").val() + ",";
        	}else{
        		chk_channel += $(this).val()+",";
        	}
    		
    	}); 
        if(!flag){
        	return false;
        }
        if(!chk_channel){
        	bootbox.balert("渠道必须选择!");
            return false;
        }
       
        
        var actBaseNub = form.actBaseNub.value;
        if (!re.test(actBaseNub))
        {
        	bootbox.balert("参奖基数必须输入数字!");
            return false;
         }

        
        //isLimitScanRegion 扫码区域是否受限
        var isLimitScanRegion = 1;//不限制
        if($("[name='isLimitScanRegion'] :checked")){
        	isLimitScanRegion = 0;//限制
        }
       
        
      //活动抽奖背景图片
        var pictures = "";
        $("#ctn_new_product_pics img").each(function () {
            pictures += $(this).data("picuri");
        });
        if(pictures == ""){//不上传抽奖背景图时，保存默认的抽奖背景图
        	pictures = "/activity/bg_start.png";
        }
        
        //活动中奖背景图片
        var pictures_win = "";
        $("#ctn_new_product_pics_win img").each(function () {
        	pictures_win += $(this).data("picuri");
        });
        if(pictures_win == ""){//不上传中奖背景图片时，保存默认的中奖背景图
        	pictures_win = "/activity/bg_red.png";
        }
        
        
        var isAutoDraw = "";
        if($("#radio_yes").is(":checked")){
        	isAutoDraw = 1;//自动抽奖
        }
        if($("#radio_no").is(":checked")){
        	isAutoDraw = 0;//不自动抽奖
        }
        if(isAutoDraw == 1){
        	pictures = "/activity/bg_start.png";
        }
        //活动未中奖背景图片
        var pictures_nowin = "";
        $("#ctn_new_product_pics_nowin img").each(function () {
            pictures_nowin += $(this).data("picuri");
        });
        if(pictures_nowin == ""){//不上传抽奖背景图时，保存默认的抽奖背景图
        	pictures_nowin = "/activity/bg_nowin.png";
        }
        var activity = {name: name, isLimitScanRegion: isLimitScanRegion, actTimeStart: actTimeStart, actTimeEnd: actTimeEnd,
        		actBaseNub: actBaseNub,selectedPros:chk_value_str,channel:chk_channel,selectedRgn:selectRgn,
        		backgroundImageGet:pictures,backgroundImageWin:pictures_win,backgroundImageLos:pictures_nowin,cashTimeEnd:actTimeEnd,isAutoDraw:isAutoDraw};

        $.postJsonBody("/activity", activity, function (re) {
        	activity_id = re.data;
        	//bootbox.balert("保存成功!");
            //window.location.href="/activity";
        	//要求跳转到中奖编辑页面
        	window.location.href="/activity/getActivityPrizeList?activityId="+activity_id;
        	
        	
        })
    });
  
    //编辑保存活动
    $("[name='btn_save_edit_activity']").click(function () {
        var form = window.form_edit_activity;
        var id = form.id.value;
        var name = form.name.value;//活动名称
        if(!name){
        	bootbox.balert("活动名称必须填写!");
        	return;
        }
        
        var num = $("[id^=regionDiv]").length;
        var str="";
        var str1 ="";
        var str2 = "";
        var str_="",str3="",str4="";
        var selectRgn="";//保存选择的区域id
        for(var i = 0; i < num; i++){
        	if(i==0){
        		str = $("[id^=regionDiv]").find("select:eq(0) option:selected").val();
        		str1 = $("[id^=regionDiv]").find("select:eq(1) option:selected").val();
        		str2 = $("[id^=regionDiv]").find("select:eq(2) option:selected").val();
        		if(str != ""){
        			if(str2 != ""){
        				if(selectRgn.indexOf(str2)<0){
        					selectRgn += str2+",";
        				}
            			
            		}else{
            			if(str1 != ""){
            				if(selectRgn.indexOf(str1)<0){
            					selectRgn += str1+",";
            				}
            				
            			}else{
            				if(str != ""){
            					if(selectRgn.indexOf(str)<0){
            						selectRgn += str+",";
            					}
            					
            				}
            			}
            		}
        		}
        		
        	}else{
        		
        		str_ = $("[name='regionDiv"+i+"']").find("select:eq(0) option:selected").val();
        		str3 = $("[name='regionDiv"+i+"']").find("select:eq(1) option:selected").val();
        		str4 = $("[name='regionDiv"+i+"']").find("select:eq(2) option:selected").val();
        		
        		if(str_ !=""){
        			if(str4 != ""){
        				if(selectRgn.indexOf(str4)<0){
        					selectRgn += str4+",";
        				}
            			
            		}else{
            			if(str3 != ""){
            				if(selectRgn.indexOf(str3)<0){
            					selectRgn += str3+",";
            				}
            				
            			}else{
            				if(str_ != ""){
            					if(selectRgn.indexOf(str_)<0){
            						selectRgn += str_ +",";
            					}
            					
            				}
            			}
            		}
        		}
        		str_="";
        		str3="";
        		str4="";
        		
        		
        	}
        }
        
        if(selectRgn=="" && ($("#regFlag").val()==0)){
        	bootbox.balert("请选择活动区域!");
            return false;
        }   
        
        var actTimeStart = new Date((form.actTimeStart.value).replace(new RegExp("-","gm"),"/")).getTime();
        var actTimeEnd = new Date((form.actTimeEnd.value).replace(new RegExp("-","gm"),"/")).getTime();
        
        if(actTimeStart=="" || actTimeEnd==""){
        	bootbox.balert("请选择活动时间!");
            return false;
        }
        
        //isLimitScanRegion 扫码区域是否受限
        var isLimitScanRegion = 1;//不限制
        if($("#isLimitScanRegion_edit").is(":checked")){
        	isLimitScanRegion = 0;//限制
        }
      //渠道
        var chk_channel = "";
        var flag = true;
        $('input[name="channel"]:checked').each(function(){
        	
        	if($(this).val() == "自定义"){
        		if($("#channel_custom").val() == null || $("#channel_custom").val()==""){
        			bootbox.balert("渠道为自定义，必须填写自定义说明!");
                    flag = false;
        		}
        		chk_channel += $("#channel_custom").val() + ",";
        	}else{
        		chk_channel += $(this).val()+",";
        	}
    		
    	}); 
        if(!flag){
        	return false;
        }
        if(!chk_channel){
        	bootbox.balert("渠道必须选择!");
        	return;
        }
        
        var re = /^[0-9]+.?[0-9]*$/;   //判断字符串是否为数字
        var actBaseNub = form.actBaseNub.value;
        if (!re.test(actBaseNub))
        {
        	bootbox.balert("参奖基数必须为数字!");
            return false;
         }
        
        
        
        //活动抽奖背景图片
        var pictures = "";
        $("#ctn_edit_product_pics img").each(function () {
            pictures += $(this).data("picuri");
        });
        //活动中奖背景图片
        var pictures_win = "";
        $("#ctn_edit_product_pics_win img").each(function () {
        	pictures_win += $(this).data("picuri");
        });
        
        if($("#product_table").html() == "" || ($("#product_table").length == 0)){
        	bootbox.balert("请选择活动商品!");
            return;
        }
        var isAutoDraw = "";
        if($("#radio_yes").is(":checked")){
        	isAutoDraw = 1;//自动抽奖
        }
        if($("#radio_no").is(":checked")){
        	isAutoDraw = 0;//不自动抽奖
        }
        if(isAutoDraw == 1){
        	pictures = "/activity/bg_start.png";
        	//pictures_win = "/activity/bg_red.png";
        }
      //活动未中奖背景图片
        var pictures_nowin = "";
        $("#ctn_edit_product_pics_nowin img").each(function () {
            pictures_nowin += $(this).data("picuri");
        });
        if(pictures_nowin == ""){//不上传抽奖背景图时，保存默认的抽奖背景图
        	pictures_nowin = "/activity/bg_nowin.png";
        }
        var activity = {id:id,name: name, isLimitScanRegion: isLimitScanRegion, actTimeStart: actTimeStart, actTimeEnd: actTimeEnd,
        		actBaseNub: actBaseNub,selectedPros:chk_value_str,channel:chk_channel,selectedRgn:selectRgn,
        		backgroundImageGet:pictures,backgroundImageWin:pictures_win,backgroundImageLos:pictures_nowin,selectedPros:chk_value_str,
        		delSelectedPros:chk_value_str_del,isAutoDraw:isAutoDraw};
//        console.log(activity);
        $.putJsonBody("/activity",activity, function (re) {
        	//bootbox.balert("保存成功!");
        	window.location.href="/activity/getActivityPrizeList?activityId="+id;
        });
    });
    

    
    
    
    
    //取消商品选择
    $("#selectPro_cancel").click(function(){
    	$("[name='selectedProduct']").hide();
    });
    //选择完商品，确认
    var oldInnerHTML = $("#product_table").html();
    $("#selectPro_confirm").click(function(){
    	//关闭商品选择页面，
    	$("[name='selectedProduct']").hide();
    	
    	//同时显示已选择的活动列表，显示位置：创建活动页面-->活动商品
    	//获取选中的记录id,根据id查询出列表，展示
    	var chk_value =[];
    	
    	$('input[name="product"]:checked').each(function(){
    		chk_value.push($(this).val());
    		chk_value_str += $(this).val()+",";
    	}); 
    	
    	if(chk_value.length == 0){
    		bootbox.balert("没有选中任何商品，请继续选择商品!");
    		return;
    	}else{
			var str = oldInnerHTML;
			for(var i= 0; i<chk_value.length; i++){

				var id = chk_value[i];
				str += '<tr>' +
					'<td>'+chk_value[i] + '</td>'+
					'<td>'+ $(".name_" +id).text() + '</td>' +
					'<td>'+ $(".number_" +id).text() + '</td>' +
					'<td>'+ $(".bar_" +id).text() + '</td>' +
					'<td>'+ $(".brand_" +id).text() + '</td>' +
					'<td><button type="button" class="btn btn-default btn-xs" onclick="delSelectedPro('+chk_value[i]+',this)" name="btn_delete_activity_product" data-activity-product-id= "' + chk_value[i] + '">删除</button></td>'+
					'</tr>';

			};
			$('#product_table').html(str);
			
		}
    	
    });
    

	function resetData(page){
		var keyword = $('input[name="keyword"]').val();

		page = page || 1;
		$.post("/activity/getProductList?keyword=" + keyword + "&page=" +page, function (re) {
			var result = re.data, resultList=result.result;

			var str = "";
			for(var i=0; i<resultList.length; i++){

				var id = resultList[i].id;
				var activityProductIdIsExists = resultList[i].activityProductIdIsExists;
				var state1 = resultList[i].state1;
				var state2 = resultList[i].state2;
				if(activityProductIdIsExists == 0){//不存在活动关联的商品，可用
					str += '<tr>' +
					'<td><input type="checkbox" name="product" value="'+id+'" onclick="chk_product()" /></td>'+
					'<td>'+ id + '</td>'+
					'<td class="name_'+id+ '">'+ resultList[i].name + '</td>' +
					'<td class="number_'+id+ '">'+ resultList[i].number + '</td>' +
					'<td class="bar_'+id+ '">'+ resultList[i].barcode + '</td>' +
					'<td class="brand_'+id+ '">'+ resultList[i].brandName + '</td>' +
					'<td>可用</td>' +
					'</tr>';
				}else{//存在活动关联的商品
					if(state1==0 && state2==0){
						str += '<tr>' +
						'<td><input type="checkbox" name="product" value="'+id+'"/></td>'+
						'<td>'+ id + '</td>'+
						'<td class="name_'+id+ '">'+ resultList[i].name + '</td>' +
						'<td class="number_'+id+ '">'+ resultList[i].number + '</td>' +
						'<td class="bar_'+id+ '">'+ resultList[i].barcode + '</td>' +
						'<td class="brand_'+id+ '">'+ resultList[i].brandName + '</td>' +
						'<td>可用</td>' +
						'</tr>';
					}else{
						str += '<tr>' +
						'<td></td>'+
						'<td>'+ id + '</td>'+
						'<td class="name_'+id+ '">'+ resultList[i].name + '</td>' +
						'<td class="number_'+id+ '">'+ resultList[i].number + '</td>' +
						'<td class="bar_'+id+ '">'+ resultList[i].barcode + '</td>' +
						'<td class="brand_'+id+ '">'+ resultList[i].brandName + '</td>' +
						'<td>不可用</td>' +
						'</tr>';
					}
				}
				
			}
			$('#product_model').html(str);
			resetPage(result.pageTotal, page);
		});
	}

	function resetPage(totalPage, currPage){
		var innerHTML = [];

		currPage = currPage || 1;

		innerHTML.push('<ul class="pagination pagination-sm no-margin">');

		if(currPage > 1){
			innerHTML.push('<li class="prev"><a href="javascript:;"><span>上一页</span></a></li><li><a href="javascript:;"><span>1</span></a></li>');
		}

		if(currPage - 4 > 1){
			innerHTML.push('<li class="bigPrev"><a href="javascript:;"><span>...</span></a></li>')
		}

		for(var i = currPage - 3; i < currPage; i++){
			if(i > 1){
				innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
			}
		}

		innerHTML.push('<li class="active"><span>', currPage,'</span></li>')

		for(var i = currPage+1; i < currPage+3; i++){
			if(i < totalPage){
				innerHTML.push('<li><a href="javascript:;"><span>',i,'</span></a></li>');
			}
		}

		if(currPage < totalPage - 3){
			innerHTML.push('<li class="bigNext"><a href="javascript:;"><span>...</span></a></li>');
		}

		if(currPage < totalPage){
			innerHTML.push('<li><a href="javascript:;"><span>', totalPage,'</span></a></li>',
				'<li class="next"><a href="javascript:;"><span>下一页</span></a></li>');
		}

		innerHTML.push("</ul>")

		$("#page_model").data("total", totalPage).html(innerHTML.join(""));

	}

	resetPage(parseInt($("#page_model").data("total")));

	$("[name='pro_query']").click(function () {
			resetData(1);
	});
	$("#page_model").on("click", "li", function () {
		if($(this).hasClass("active")){
			return false;
		}

		var currPage = parseInt($("#page_model .active").text()),
			totalPage = $("#page_model").data("total");
		if($(this).hasClass("prev")){
			currPage--;
		} else if($(this).hasClass("next")){
			currPage++;
		} else if($(this).hasClass("bigPrev")){
			currPage -= 5;

			if(currPage < 1){
				currPage = 1;
			}
		} else if($(this).hasClass("bigNext")){
			currPage += 5;

			if(totalPage - currPage < 0){
				currPage = totalPage;
			}
		} else {
			currPage = parseInt($(this).text());
		}

		resetData(currPage);
	})

	//上传抽奖背景图片
    $("[name='btn_new_product_upload_pic']").click(function () {
        var uploaded_count = $("#ctn_new_product_pics").find("img").length;
        if (uploaded_count < 1) {
            $("#ipt_new_product_upload_pic").click();
        } else {
            bootbox.balert("抽奖背景图只能上传1张图片");
            return;
        }
    });
	
    $('#ipt_new_product_upload_pic').fileupload({
        dataType: 'json',
        url: "/upload/pic?type=3",
        done: function (e, data) {
            var res = data.jqXHR.responseJSON;
            var $imgEle = $("<img src='" + PicDomain + res.data + "' data-picuri='" + res.data + "'/>");
            $imgEle.click(function () {
            	bootbox.bconfirm("确定要中奖背景图吗？删除后将显示默认图片", function (re) {
					if(re){
						$imgEle.remove();
						$("#ctn_new_product_pics").siblings(".btn-default").removeData("img");
					}
            	});
            });
            $("#ctn_new_product_pics").append($imgEle).siblings(".btn-default").data("img", PicDomain + res.data);
        }
    });
    
  //上传中奖背景图片
    $("[name='btn_new_product_upload_pic_win']").click(function () {
        var uploaded_count = $("#ctn_new_product_pics_win").find("img").length;
        if (uploaded_count < 1) {
            $("#ipt_new_product_upload_pic_win").click();
        } else {
            bootbox.balert("中奖背景图只能上传1张图片");
            return;
        }
    });
    $('#ipt_new_product_upload_pic_win').fileupload({
        dataType: 'json',
        url: "/upload/pic?type=3",
        done: function (e, data) {
            var res = data.jqXHR.responseJSON;
            var $imgEle = $("<img src='" + PicDomain + res.data + "' data-picuri='" + res.data + "'/>");
            $imgEle.click(function () {
            	bootbox.bconfirm("确定要删除中奖背景图吗？删除后将显示默认图片", function (re) {
					if(re){
						$imgEle.remove();
						$("#ctn_new_product_pics_win").siblings(".btn-default").removeData("img");
					}
            	});
            });
            $("#ctn_new_product_pics_win").append($imgEle).siblings(".btn-default").data("img", PicDomain + res.data);
        }
    });
	
    //上传未中奖背景图片
    $("[name='btn_new_product_upload_pic_nowin']").click(function () {
    	console.log("上传未中奖背景图片");
        var uploaded_count = $("#ctn_new_product_pics_nowin").find("img").length;
        if (uploaded_count < 1) {
            $("#ipt_new_product_upload_pic_nowin").click();
        } else {
            bootbox.balert("中奖背景图只能上传1张图片");
            return;
        }
    });
    $('#ipt_new_product_upload_pic_nowin').fileupload({
        dataType: 'json',
        url: "/upload/pic?type=3",
        done: function (e, data) {
            var res = data.jqXHR.responseJSON;
            var $imgEle = $("<img src='" + PicDomain + res.data + "' data-picuri='" + res.data + "'/>");
            $imgEle.click(function () {
            	bootbox.bconfirm("确定要删除中奖背景图吗？删除后将显示默认图片", function (re) {
					if(re){
						$imgEle.remove();
						$("#ctn_new_product_pics_nowin").siblings(".btn-default").removeData("img");
					}
            	});
            });
            $("#ctn_new_product_pics_nowin").append($imgEle).siblings(".btn-default").data("img", PicDomain + res.data);
        }
    });

    //加载异步数据,默认获取省份信息，即父节点id为1的信息
    $.get("/region?parentId=1", function (re) {
        var regionList = re.data;
        var form = window.form_new_activity;
        var regionOptions = "";
        for (var i in regionList) {
            var region = regionList[i];
            regionOptions += "<option value='" + region.id + "'>" + region.name + "</option>";
        }
        if(window.form_new_activity != null){
        	$(window.form_new_activity.provinceId).append(regionOptions);
        }
        if(window.form_edit_activity != null){
        	$(window.form_edit_activity.provinceId).append(regionOptions);
        }
    });
    
    //选择完省时，触发查询市信息
    $("[name='provinceId']").change(function () {
    	$("#city").find("option").remove();//清空select的option
        $.get("/region?parentId=" + $('#province option:selected') .val(),function(re){
        	var cityList = re.data;
        	var form = window.form_new_activity;
        	var cityOptions = "<option value=''>请选择市</option>";
        	for(var i in cityList){
        		var city = cityList[i];
        		cityOptions += "<option value='" + city.id + "'>" + city.name + "</option>"
        	}
        	if(window.form_new_activity != null){
        		$(window.form_new_activity.cityId).append(cityOptions);
        	}
        	
        	if(window.form_edit_activity != null){
        		$(window.form_edit_activity.cityId).append(cityOptions);
        	}
        });
    });
  //选择完市时，触发查询区县信息
    $("[name='cityId']").change(function () {
    	$("#county").find("option").remove();//清空select的option
        $.get("/region?parentId=" + $('#city option:selected') .val(),function(re){
        	var countyList = re.data;
        	var form = window.form_new_activity;
        	var countyOptions = "<option value=''>请选择区县</option>";
        	for(var i in countyList){
        		var county = countyList[i];
        		countyOptions += "<option value='" + county.id + "'>" + county.name + "</option>"
        	}
        	if(window.form_new_activity != null){
        		$(window.form_new_activity.countyId).append(countyOptions);
        	}
        	if(window.form_edit_activity != null){
        		$(window.form_edit_activity.countyId).append(countyOptions);
        	}
        });
    });
    
    //添加区域 ，放在form_new_activity下
    $("[name='btn_add_regionDiv']").click(function(){
    	var new_div = $("#regionDiv").clone(false);
    	
    	//修改新div的id
    	var num = $("[id^=regionDiv]").length;
    	new_div.attr("id","regionDiv"+num);
    	new_div.attr("name","regionDiv"+num);
    	
    	//修改新的div中select的id和name,并给select添加 change事件
    	new_div.find("label").attr("name","namelabel"+num);
    	new_div.find("select:eq(0)").attr("id","province"+num);
    	new_div.find("select:eq(0)").attr("name","province"+num);
    	new_div.find("select:eq(1)").attr("id","city"+num);
    	new_div.find("select:eq(1)").attr("name","cityId"+num);
    	new_div.find("select:eq(2)").attr("id","county"+num);
    	new_div.find("select:eq(2)").attr("name","countyId"+num);
    	
    	new_div.find("[name='province"+num+"']").bind("change",function(){
			//new_div.find("select:eq(1) option").remove();//清空select的option
			new_div.find("[name='cityId"+num+"']  option").remove();
	        $.get("/region?parentId=" + $(this).find("option:selected").val(),function(re){
	        	var cityList = re.data;
	        	var form = window.form_new_activity;
	        	var cityOptions = "<option value=''>请选择市</option>";
	        	for(var i in cityList){
	        		var city = cityList[i];
	        		cityOptions += "<option value='" + city.id + "'>" + city.name + "</option>"
	        	}
	        	new_div.find("[name='cityId"+num+"']").append(cityOptions);
	        });
    		
    	});
    	
    	
    	new_div.find("[name='cityId"+num+"']").bind("change",function(){
    		//new_div.find("select:eq(2) option").remove();//清空select的option
    		new_div.find("[name='countyId"+num+"']  option").remove();
    		var pid = $(this).find("option:selected").val();
            $.get("/region?parentId=" + pid,function(re){
            	var countyList = re.data;
            	var form = window.form_new_activity;
            	var countyOptions = "<option value=''>请选择区县</option>";
            	for(var i in countyList){
            		var county = countyList[i];
            		countyOptions += "<option value='" + county.id + "'>" + county.name + "</option>"
            	}
            	new_div.find("[name='countyId"+num+"']").append(countyOptions);
               // $(window.form_edit_activity.cityId).append(cityOptions);
            });
    	});
    	
    	//删除新div中的指定内容
    	new_div.find("button").remove();
    	//去掉label内容，保留样式
    	new_div.find("[name='namelabel"+num+"']").html("");
    	//添加删除按钮
    	var btn = '<button type="button" class="btn-default" onclick="btnAction(this)" name="btn_del_regionDiv'+num+'">'+'<i class="fa fa-plus"></i>删除</button>'
    	//new_div.append(btn);
    	new_div.find("div").find("select:eq(2)").after(btn);
        new_div.insertAfter("#regionDiv");
    });
});

//删除区域
function btnAction(re){
	$(re).parent().parent().remove();
}



//预览图片
$("#preview_dialog").on("show.bs.modal", function(event){
	var _e = $(event.relatedTarget),
		url = _e.data("url") + "?img=" + (_e.data("img") || "");
	
	$(this).find("iframe").attr("src", url);
});

//选择商品页面，点击【查询】按钮后，checkbox相关操作
var flag1 = 0;
function chk_product(){
	$("input[name='product']").each(function(){
		if(!$(this).is(':checked')){
			flag1 ++;
		}
	});
	if(flag1 > 0){
		$("#selectAll").prop("checked",false);
	}else{
		$("#selectAll").prop("checked",true);
	}
	flag1 = 0;//清空falg值
}


//选择完商品,点击删除按钮操作
function delSelectedPro(id,dom){
	
	chk_value_str = chk_value_str.substring(0,chk_value_str.length-1);
	var strArray = chk_value_str.split(",");
	chk_value_str = "";
	for(var i=0;i<strArray.length;i++){
		if(strArray[i]!=id){
			chk_value_str += strArray[i]+","
		}
	}
	
	$(dom).parent().parent().remove();
}
//编辑页面，删除已选择的商品
function del(id,dom){
	chk_value_str_del += id+",";
	$(dom).parent().parent().remove();
}





 
 /**   
 *转换long值为日期字符串   
 * @param l long值   
 * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss   
 * @return 符合要求的日期字符串   
 */    

 function getFormatDateByLong(l, pattern) {  
     return getFormatDate(new Date(l), pattern);  
 }
 /**   
  *转换日期对象为日期字符串   
  * @param l long值   
  * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss   
  * @return 符合要求的日期字符串   
  */    
  function getFormatDate(date, pattern) {  
      if (date == undefined) {  
          date = new Date();  
      }  
      if (pattern == undefined) {  
          pattern = "yyyy-MM-dd hh:mm:ss";  
      }  
      return date.format(pattern);  
  }
//扩展Date的format方法   
  Date.prototype.format = function (format) {  
      var o = {  
          "M+": this.getMonth() + 1,  
          "d+": this.getDate(),  
          "h+": this.getHours(),  
          "m+": this.getMinutes(),  
          "s+": this.getSeconds(),  
          "q+": Math.floor((this.getMonth() + 3) / 3),  
          "S": this.getMilliseconds()  
      }  
      if (/(y+)/.test(format)) {  
          format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
      }  
      for (var k in o) {  
          if (new RegExp("(" + k + ")").test(format)) {  
              format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));  
          }  
      }  
      return format;  
  } 
